<template>
  <div class="pager">
    <ul>
      <li :class="{disabled:page==1}" @click="handlePage(1)">首页</li>
      <li :class="{disabled:page==1}" @click="handlePage(page - 1)">上一页</li>
      <li
        v-for="item in pageBoxArr"
        :key="item"
        :class="{focus:item==page}"
        @click="handlePage(item)"
      >{{item}}</li>
      <li :class="{disabled:page==maxPageNumber}" @click="handlePage(page + 1)">下一页</li>
      <li :class="{disabled:page==maxPageNumber}" @click="handlePage(maxPageNumber)">尾页</li>
      <li>
        <span>{{page}}</span>
        <span>/</span>
        <span>{{maxPageNumber}}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: {
    page: {
      // 当前页码
      type: Number,
      default: 1
    },
    total: {
      // 总新闻条数
      type: Number,
      default: 1000
    },
    limit: {
      // 每页显示条数
      type: Number,
      default: 10
    },
    pageBox: {
      // 最多显示多少个数字页码
      type: Number,
      default: 10
    }
  },
  computed: {
    // 总页数
    maxPageNumber() {
      return Math.ceil(this.total / this.limit / 7);
    },
    // 最小数字页码
    minPageBox() {
      let pg = this.page - this.pageBox / 2;
      pg = pg < 1 ? 1 : pg;
      return pg;
    },
    // 最大数字页码
    maxPageBox() {
      let pg = this.minPageBox + this.pageBox - 1;
      pg = pg > this.maxPageNumber ? this.maxPageNumber : pg;
      return pg;
    },
    pageBoxArr() {
      let arr = [];
      for (let i = this.minPageBox; i <= this.maxPageBox; i++) {
        arr.push(i);
      }
      return arr;
    }
  },
  methods: {
    handlePage(newPage) {
      if (newPage < 1) {
        newPage = 1;
      } else if (newPage > this.maxPageNumber) {
        newPage = this.maxPageNumber;
      }
      this.$emit("pageChange", newPage);
    }
  }
};
</script>

<style lang="less" scoped>
.pager {
  user-select: none;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  ul {
    // display: flex;
    li {
      float: left;
      cursor: pointer;
      padding: 5px 10px;
      border: 1px solid #000;
      margin-right: 10px;
      &:last-child {
        border: none;
        margin: 0;
      }
    }
  }
}

.disabled {
  border-color: #ccc !important;
  color: #ccc;
}
.focus {
  border: 1px solid transparent !important;
}
</style>